package com.zjl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjl.common.BaseContext;
import com.zjl.common.CustomException;
import com.zjl.entity.*;
import com.zjl.mapper.OrdersMapper;
import com.zjl.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 提交订单信息，涉及订单表orders、订单明细表order_detail；对前端传来的order对象需要手动设置其他属性，因此涉及到地址薄表address_book查询与用户表user查询。
     * 订单明细表的插入需要在购物车中查询，并将购物车对象的属性赋予订单明细对象。
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //order对象属性种只有addressBookId、payMethod、remark有值。
        //需要设置userId、订单状态status（1待付款，2待派送，3已派送，4已完成，5已取消）、phone、user_name、
        //地址address、订单号、实收金额amount、下单时间orderTime

        //查询当前用户
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId,BaseContext.getCurrent());
        User serviceUser = userService.getOne(userWrapper);

        //为订单设置用户信息
        orders.setUserId(serviceUser.getId());
        orders.setStatus(2);
        orders.setPhone(serviceUser.getPhone());
        orders.setUserName(serviceUser.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //为订单设置详细地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("地址为空！");
        }
        String address=
                (addressBook.getProvinceName()!=null?addressBook.getProvinceName():"")+
                        (addressBook.getCityName()!=null?addressBook.getProvinceName():"")+
                        (addressBook.getDistrictName()!=null?addressBook.getDistrictName():"")+
                        addressBook.getDetail();
        orders.setAddress(address);

        //设置订单号
        Long orderId =IdWorker.getId();
        orders.setNumber(String.valueOf(orderId));

        //设置实收金额
            //查询当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrent());
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

            //AtomicInteger原子操作保障在多线程中不出错
        AtomicInteger amount=new AtomicInteger(0);

        //得到订单明细列表对象
        List<OrderDetail> orderDetails=shoppingCarts.stream().map(item->{
            OrderDetail orderDetail = new OrderDetail();
            //将shoppingCart属性值对应赋给orderDetail，由于二者属性不是包含关系，所以无法用BeanUtils.BeanUtils.copyProperties()
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());

            //相当于“+=” intValue()：输出为int
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());

        orders.setAmount(new BigDecimal(amount.get()));

        //在订单表保存订单
        this.save(orders);

        //在订单明细表批量保存数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(wrapper);
    }
}
